import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import './ProjectsPage.css'; // 复用样式
import { projectGroupApi } from '../../services/api';

const CreateProjectGroupPage = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [projectGroup, setProjectGroup] = useState({
    name: '',
    description: ''
  });

  const handleChange = (e) => {
    const { name, value } = e.target;
    setProjectGroup(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    
    try {
      console.log('创建项目组:', projectGroup);
      const response = await projectGroupApi.addProjectGroup(projectGroup);
      if (response.code === 200 && response.data) {
        alert('创建项目组成功');
        navigate('/project-groups'); // 创建成功后返回项目组列表页面
      } else {
        alert(`创建项目组失败: ${response.message}`);
      }
    } catch (error) {
      console.error('创建项目组异常:', error);
      alert(`创建项目组异常: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    navigate('/project-groups'); // 取消后返回项目组列表页面
  };

  return (
    <div className="projects-page">
      <div className="page-header">
        <h1>创建项目组</h1>
      </div>

      <div className="form-container">
        <form onSubmit={handleSubmit}>
          <div className="form-group">
            <label htmlFor="name">项目组名称</label>
            <input
              type="text"
              id="name"
              name="name"
              value={projectGroup.name}
              onChange={handleChange}
              required
              placeholder="请输入项目组名称"
              className="form-control"
            />
          </div>
          
          <div className="form-group">
            <label htmlFor="description">项目组描述</label>
            <textarea
              id="description"
              name="description"
              value={projectGroup.description}
              onChange={handleChange}
              placeholder="请输入项目组描述"
              rows="4"
              className="form-control"
            ></textarea>
          </div>
          
          <div className="form-actions">
            <button 
              type="button" 
              className="cancel-button" 
              onClick={handleCancel}
              disabled={loading}
            >
              取消
            </button>
            <button 
              type="submit" 
              className="submit-button" 
              disabled={loading}
            >
              {loading ? '提交中...' : '创建项目组'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default CreateProjectGroupPage;
